package 多线程交替打印ABC;

import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/***
 * 使用信号量交替打印ABC
 */
public class SolutionSemaphore {
    private static Semaphore semaphore1 = new Semaphore(1);
    private static Semaphore semaphore2 = new Semaphore(0);
    private static Semaphore semaphore3 = new Semaphore(0);
    private static AtomicInteger num = new AtomicInteger(3);

    public static void main(String[] args) {
        int printNum = 3;
        new Thread(new Print("A", semaphore1, semaphore2, printNum)).start();
        new Thread(new Print("B", semaphore2, semaphore3, printNum)).start();
        new Thread(new Print("C", semaphore3, semaphore1, printNum)).start();
    }

    private static class Print implements Runnable {
        private String name;
        private Semaphore current;
        private Semaphore next;
        private int num;

        Print(String name, Semaphore current, Semaphore next, int num) {
            this.name = name;
            this.current = current;
            this.next = next;
            this.num = num;
        }

        @Override
        public void run() {
            while (num > 0) {
                try {
                    current.acquire();
                    System.out.println(name);
                    next.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                --num;
            }
        }
    }

}
